<template>
  <div>
    <el-tree
      :data="data"
      node-key="highId"
      draggable
      ref="selectTree"
      :expand-on-click-node="false"
      :highlight-current="true"
      :default-expand-all="true"
      @node-drop="handleDrop"
      @node-click="handleClick"
      :allow-drop="allowDrop"
      :current-node-key="highlightedNodeId"
    >
      <div class="custom_tree_node" slot-scope="{ data }">
        <div
          @dblclick="handleEmit(data, 'rename')"
          v-if="!data.showRename"
          :style="{ width: `calc(280px - 90px - ${(data.level - 1) * 16}px` }"
          class="label"
        >
        {{ data.name }}
        </div>
        <div
          v-if="data.showRename"
          :style="{ width: `calc(280px - 90px - ${(data.level - 1) * 16}px` }"
          class="label"
        >
          <el-input
            v-input-restrict
            clearable
            size="small"
            ref="resetName"
            @focus="selectAllText"
            @blur="editName(data)"
            @change="editName(data, 2)"
            v-model="data.name"
            placeholder="请输入名称"
            style="width: 100%"
          />
        </div>
        <div class="flex_center">
          <!-- <div class="must_learn" v-if="data.type == 0">必学</div>
          <div class="choose_learn" v-if="data.type == 1">选学</div> -->
          <div v-if="type == 'add' || type == 'edit'" class="btn">
            <el-dropdown placement="bottom-start" trigger="click">
              <img
                class="more"
                src="@/assets/images/courseadd/more.png"
                alt=""
                @click.stop=""
              />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-if="data.level == 1"
                  @click.native.stop="handleEmit(data, 'addLink')"
                >
                  <span>添加子步骤</span>
                </el-dropdown-item>
                <el-dropdown-item
                  @click.native.stop="handleEmit(data, 'rename')"
                >
                  <span>重命名</span>
                </el-dropdown-item>
                <el-dropdown-item
                  @click.native.stop="handleEmit(data, 'delete')"
                >
                  <span>删除</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
    </el-tree>
  </div>
</template>

<script>
export default {
  name: "courseTrees",
  data() {
    return {
      autofocus: true,
      selectId: "",
      courseIndexTree: [],
    };
  },
  props: {
    highlightedNodeId: {
      type: [String, Number],
      default: "",
    },
    data: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: "add",
    },
  },
  watch: {
    data: {
      handler(newValue, oldValue) {},
      deep: true,
    },
    highlightedNodeId(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.$nextTick(() => {
          this.$refs.selectTree.setCurrentKey(newValue);
        });
      }
    },
  },
  mounted() {},
  methods: {
    selectAllText() {
      this.$nextTick(() => {
        this.$refs.resetName.$refs.input.select();
      });
    },
    // inputfoucus
    inputfoucus() {
      this.$nextTick(() => {
        this.$refs["resetName"].focus();
      });
    },
    // 点击某个节点
    handleClick(data) {
      this.$emit("handleClick", data);
    },
    //设置子目录可以拖拽
    allowDrop(draggingNode, dropNode, type) {
      //注掉的是同级拖拽
      if (draggingNode.level === dropNode.level) {
        // 获取父节点信息
        const draggingParent = draggingNode.parent;
        const dropParent = dropNode.parent;
        if (draggingParent !== dropParent) {
          return false;
        }
        return type === "prev" || type === "next";
      } else {
        // 不同级进行处理
        return false;
      }
    },
    expandAll() {
      this.$nextTick(() => {
        this.expandAllNodes(this.$refs.selectTree.store.root);
      });
    },
    collapseAll() {
      this.$nextTick(() => {
        this.collapseAllNodes(this.$refs.selectTree.store.root);
      });
    },
    expandAllNodes(node) {
      if (node) {
        node.expanded = true;
        if (node.childNodes) {
          node.childNodes.forEach((childNode) => {
            this.expandAllNodes(childNode);
          });
        }
      }
    },
    collapseAllNodes(node) {
      if (node) {
        node.expanded = false;
        if (node.childNodes) {
          node.childNodes.forEach((childNode) => {
            this.collapseAllNodes(childNode);
          });
        }
      }
    },
    // 拖拽排序
    async handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("tree drop: ", draggingNode, dropNode, dropType, ev);
      let parentChildren = this.findParentChildrenById(
        this.data,
        draggingNode.data.id,
        draggingNode.data.level
      );
      let ids = [];
      if (parentChildren) {
        parentChildren.forEach((item, index) => {
          ids.push(item.id);
        });
        console.log(ids);
        this.$emit("sort", {
          level: draggingNode.data.level,
          arr: ids,
        });
      }
    },
    //返回节点所在层级的父节点的 children 数组
    findParentChildrenById(data, checkId, level, parentChildren = null) {
      if (level == 1) {
        let firstChildren = [];
        for (let item of data) {
          firstChildren.push(item);
        }
        return firstChildren;
      }
      for (let item of data) {
        if (item.id === checkId) {
          return parentChildren;
        }
        if (item.children) {
          let result = this.findParentChildrenById(
            item.children,
            checkId,
            level,
            item.children
          );
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
    handleEmit(data, name) {
      if (name == "rename") {
        data.showRename = true;
        this.$nextTick(() => {
          this.$refs["resetName"].focus();
        });
      } else {
        this.$emit(name, data);
      }
    },
    // 2为change 1为blur
    editName(data, type) {
      console.log(data,type);
      if (type == 2) {
        if (data.name) {
          this.$emit("rename", data);
        } else {
          this.$modal.msg(`名称不能为空`);
          data.name = data.taskName || data.chapterName;
        }
      } else {
        data.showRename = false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.custom_tree_node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px 0 0;
  box-sizing: border-box;
  .flex_center {
    display: flex;
    align-items: center;
    .must_learn {
      color: rgb(40, 178, 139);
      background: rgb(196, 236, 226);
      width: 40px;
      height: 16px;
      border-radius: 8px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .choose_learn {
      color: rgb(44, 172, 255);
      background: rgb(213, 238, 255);
      width: 40px;
      height: 16px;
      border-radius: 8px;
      font-size: 12px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .btn {
      width: 20px;
      height: 20px;
      overflow: hidden;
      margin-left: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      .more {
        width: 18px;
        height: 12px;
      }
    }
  }
  .label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
::v-deep .el-tree-node__content {
  height: 40px;
}
</style>
